package acwing.bfs;

import java.io.BufferedInputStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * 走迷宫
 *
 * @author yang
 * @date 2021/11/28
 */
public class 走迷宫 {

    static int N = 110;
    static int n, m;
    //表示迷宫
    private static int[][] g = new int[N][N], d = new int[N][N];
    //用数组来表示
    private static Queue<q> queue = new LinkedList<>();
    public static void main(String[] args) {
        Scanner in = new Scanner(new BufferedInputStream(System.in));
        //n行m列
        n = in.nextInt();
        m = in.nextInt();
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= m; j++)
                g[i][j] = in.nextInt();
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                d[i][j] = -1;
            }
        }

        System.out.println(bfs());
    }

    private static int bfs() {
        int []dx = {-1,0,1,0}, dy = {0,1,0,-1};
        queue.add(new q(0,0));
        d[0][0] = 0;//标记第一个位置已走过
        while (!queue.isEmpty()) {
            q temp = queue.poll();
            for (int i = 0; i < 4; i++) {
                int x = temp.x + dx[i];
                int y = temp.y + dy[i];
                if (x >= 0 && x < n && y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0) {
                    d[x][y] = d[temp.x][temp.y] + 1;
                    queue.add(new q(x,y));
                }
            }

        }
        return d[n - 1][m - 1];
    }
}

class q {
    int x;
    int y;

    public q(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
